#include "MailBoxMgr.h"
#include "../RelaSvr.h"
#include "dbProto/dbTableDef.h"
#include "db_driver/db_driver.h"
#include "stl_boost.h"
#include "RelaPlayerMgr.h"

using namespace su;
using namespace std;
using namespace proto;

MailBoxMgr& gMailBoxMgr = MailBoxMgr::Ins();

#define RegRpc(fun) STATIC_RUN(RelaSvr::Ins().RegRpcFun(&MailBoxMgr::fun, MailBoxMgr::Ins(), #fun);)

MailBox* MailBoxOptMgr::OnFindTarget(uint64 id)
{
	MailBox* p = gMailBoxMgr.Find(id);
	if (nullptr == p)
	{
		return nullptr;
	}

	p->Touch();
	return p;
}

void MailBoxOptMgr::OnMissTarget(uint64 id)
{
	auto f = [id](const std::string& data)
	{
		if (data.empty())
		{
			LERROR("load mailBox fail", id);
			MailBoxOptMgr::Ins().OnLoadFail(id);
		}
		else
		{
			auto& id2data = gMailBoxMgr.m_id2data;
			auto it = id2data.find(id);
			L_COND_V( it == id2data.end());

			MailBox& mailBox = id2data.emplace(id, id).first->second;
			TableCfg::Ins().UnpackForObj(mailBox.m_db, data);
			mailBox.AfterLoadFromDb();
			MailBoxOptMgr::Ins().OnLoadOk(id, mailBox);
		}
	};
	
	string cond = "id = " + StrNum::NumToStr(id);
	Dbproxy::Ins().QueryCondRaw(MAIL_BOX_TABLE_ID, cond, f);
}

MailBox *MailBoxMgr::Find(uint64 id)
{
	return su::MapFind(m_id2data, id);
}

void MailBoxMgr::OnFiveMinute()
{
	for (auto&& [k,v] : m_id2data)
	{
		v.SaveDb();
	}
}

void MailBoxMgr::OnHalfHour()
{
	
}

RegRpc(AddMail) 
void MailBoxMgr::AddMail(uint64 id, uint32 cfgid, const std::string &attachment)
{
	auto ok = [cfgid, attachment](MailBox& box)
	{
		box.AddMail(cfgid, attachment);
	};
	auto fail = [](uint64 id)
	{
		LERROR("AddMail fail"); 
	};
	 MailBoxOptMgr::Ins().AddOpt(id, ok, fail);
}